<?php

namespace Frieza\Modules\Userprofile\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\advertisement\MHhzPositionUserprofile;
use Biz\service\advertisement\AdUserProfileManagement;
use Doraemon\service\position\DisplayConstInterface;
use Doraemon\service\position\UserProfileModule\Area;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class IndexController extends Controller
{

    public function index(Request $request, Content $content)
    {
        $entity = new MHhzPositionUserprofile;

        $params = $request->all();
        $sign = $params['sign'] ?? $entity::SIGN_TYPE_FIELD;
        $sort = strlen($params['field']) == 0;
        $showField = $sign == $entity::SIGN_TYPE_FIELD;

        $labels = [];
        $groups = [];
        $fields = [];
        $list = AdUserProfileManagement::getConf();
        if ($list) {
            foreach ($list as $k => $v) {
                $v['id'] = $k;
                if ($v['sign'] == $entity::SIGN_TYPE_GROUP) {
                    $group[$v['column_field']] = $v['column_name'];
                    $groups[] = $v;
                } elseif ($v['sign'] == $entity::SIGN_TYPE_LABEL) {
                    $labels[] = $v;
                }else {
                    $fields[$v['group_field']][] = $v;
                }
            }
        }
        $group[''] = '-';

        $list = [];
        if ($sign == $entity::SIGN_TYPE_FIELD) {
            foreach ($group as $column_field => $name) {
                $list = array_merge($list, $fields[$column_field] ?? []);
            }
        }

        if ($sign == $entity::SIGN_TYPE_LABEL) $list = $labels;
        if ($sign == $entity::SIGN_TYPE_GROUP) $list = $groups;
        $manageList = [];
        foreach ($list as $v) {
            if (isset($v['column_alias'])) {
                $bool = $params['field'] && (strpos($v['column_field'], $params['field']) === false) && (strpos($v['column_alias'], $params['field']) === false);
            } else {
                $bool = $params['field'] && (strpos($v['column_field'], $params['field']) === false);
            }
            if ($bool) continue;
            $manageList[] = $v;
        }

        $gridModel = new pGridDataModel($manageList);
        $sortUrl = route('userprofile.sort');
        $gridMap = Admin::grid($gridModel,
            function (Grid $grid) use ($request, $group, $sortUrl, $entity, $sort, $showField) {
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disablePagination();
                $grid->disableActions();
                $grid->filter(function (Grid\Filter $filter) use ($entity) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->equal('sign', '类型')->select($entity::SIGN_TYPE_MAP)->default($entity::SIGN_TYPE_FIELD);
                    $filter->equal('field', '标识/别名');
                    //条件展开
                    $filter->expand();
                });

                if ($sort) {
                    $grid->column('id', '配置ID')->sort($sortUrl);
                } else {
                    $grid->column('id', '配置ID');
                }
                $grid->column('info', '信息')->display(function () use ($group, $entity) {
                   /**
                    * @var MHhzPositionUserprofile $this
                   */
                   $display = [
                       '标识 : ' . $this->column_field,
                       '名称 : ' . $this->column_name,
                   ];
                   if ($this->column_alias) $display[] = '别名 : ' . $this->column_alias;
                    return implode('<br/>', $display);
                });
                $grid->column('show_option', '加载显示')->select($entity::SHOW_OPTION_MAP);
                if ($showField) {
                    $grid->column('group_field', '组信息')->select($group);
                    $grid->column('form_type', '表单类型')->select(DisplayConstInterface::ADM_FORM_TYPE_MAP);
                    $grid->column('switch_name', '开关名称')->editable();
                    $grid->column('form_help', '帮助描述')->width(300)->editable();
                }
            });
        $title = '用户分群配置管理';
//
        $aliasPath = AdUserProfileManagement::ALIAS_PATH;
        $confPath = AdUserProfileManagement::CONF_PATH;
        $aliasScript = "/data/wwwroot/g_biz/cli/ad/userprofileMakeAlias.php";
        $createScript = "/data/wwwroot/g_biz/cli/ad/userprofileCreate.php";
        $hitScript = "/data/wwwroot/g_biz/cli/ad/userprofileHit.php";
        $esScript = "/data/wwwroot/g_biz/cli/ad/userprofileEs.php";

        $message = [
            '开发步骤 : ',
            "1.online环境通过脚本 php {$aliasScript} 获取配置,写入dev环境 {$aliasPath}",
            "2.dev环境通过脚本 php {$createScript} 生成配置,从开发机下载 {$confPath}",
            "3.检查form显示, 方法入口:\Doraemon\service\position\UserProfileModule::formDisplay",
            "4.检查form保存, 方法入口:\Doraemon\service\position\AdmOperationModule::addUserProfile",
            "5.检查grid显示, 方法入口:\Doraemon\service\position\UserProfileModule::display",
            "6.检查单点匹配, php {$hitScript} 5204625 20 9,10 \"is_advisory:1;action_interest_tag_1m:家饰搭配;\"",
            "7.检查es查询uid, php {$esScript} 9,10 20 1 5000",
        ];
        $html = \Doraemon\tools\Msg2Admin::html('提示', implode('<br/>', $message));
        $content->body($html);

        return $content
            ->header($title)
            ->description(' ')
            ->breadcrumb(['text' => $title])
            ->row($gridMap);
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        if ($sortInfo) {
            AdUserProfileManagement::sort($sortInfo);
        }
    }

    public function area(Request $request)
    {
        $pid = $request->input('q', 0);
        $areas = Area::getLocation($pid);
        $format = array_map(function($k, $v){
            return [
                'id' => $k,
                'text' => $v,
            ];
        }, array_keys($areas), $areas);
        return response()->json($format);
    }

    protected static function opAuth()
    {
        if (!HhzEnv::isShopTest()) throw new \Exception('开发环境操作');
    }

    public function quickSave(Request $request, $id = 0)
    {
        $request = $request->all();

        return \Doraemon\tools\Msg2Admin::simpleMethod(function() use ($request, $id) {
            self::opAuth();
            $name = $request['name'] ?? '';
            $value = $request['value'] ?? '';
            $id = $request['pk'] ?? $id;
            $data = [];
            if (isset($request['group_field'])) {
                $name = 'group_field';
                $value = $request['group_field'];
            }
            if (isset($request['show_option'])) {
                $name = 'show_option';
                $value = $request['show_option'];
            }
            if (isset($request['form_type'])) {
                $name = 'form_type';
                $value = $request['form_type'];
            }
            switch ($name) {
                case 'form_type':
                    $data['form_type'] = $value;
                    break;
                case 'show_option':
                    $data['show_option'] = $value;
                    break;
                case 'group_field':
                    $data['group_field'] = $value;
                    break;
                case 'switch_name':
                    $data['switch_name'] = $value;
                    break;
                case 'form_help':
                    $data['form_help'] = $value;
                    break;
                default:
                    throw new \Exception('未定义的快速更新字段');
            }

            if (is_numeric($id) && $data) {
                $conf = AdUserProfileManagement::getConf();
                if (!isset($conf[$id])) throw new \Exception('配置缺失');
                $conf[$id] = $data + $conf[$id];
                AdUserProfileManagement::setConf($conf);
            }
        });
    }
}
